//
//  MHLoginViewController.m
//  ManHua
//
//  Created by 江子安 on 15/10/28.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHLoginViewController.h"
#import "MHRegistViewController.h"
#import "MHDataManager.h"
#import "MHUserInfoSington.h"
#import <SDWebImageManager.h>
#import <AFNetworking.h>

#define mainSize    [UIScreen mainScreen].bounds.size

#define offsetLeftHand      60

#define rectLeftHand        CGRectMake(61-offsetLeftHand, 90, 40, 65)
#define rectLeftHandGone    CGRectMake(mainSize.width / 2 - 100, vLogin.frame.origin.y - 22, 40, 40)

#define rectRightHand       CGRectMake(imgLogin.frame.size.width / 2 + 60, 90, 40, 65)
#define rectRightHandGone   CGRectMake(mainSize.width / 2 + 62, vLogin.frame.origin.y - 22, 40, 40)

typedef NS_ENUM(NSInteger, JxbLoginShowType) {
    JxbLoginShowType_NONE,
    JxbLoginShowType_USER,
    JxbLoginShowType_PASS
};

@interface MHLoginViewController()<UITextFieldDelegate>
{
    UITextField* txtUser;
    UITextField* txtPwd;
    
    UIImageView* imgLeftHand;
    UIImageView* imgRightHand;
    
    UIImageView* imgLeftHandGone;
    UIImageView* imgRightHandGone;
    
    JxbLoginShowType showType;
}
@property (nonatomic, strong) UITextField *userTF;
@property (nonatomic, strong) UITextField *passwordTF;
@property (nonatomic, assign) BOOL result;
@property (nonatomic, strong) MHUserInfo *userInfo;
@property (nonatomic, strong) UITextField *currentTF;

@end

@implementation MHLoginViewController

- (void)dealloc
{
    NSLog(@"MHLoginViewController ++++ dealloc");
}

- (MHUserInfo *)userInfo
{
    if (_userInfo == nil) {
        _userInfo = [[MHUserInfo alloc]init];
    }
    return _userInfo;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"登陆";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismissLoginVC)];
    self.navigationController.navigationBar.tintColor = kThemeColor;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    [self registerForKeyboardNotifications];

    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    UIImageView* imgLogin = [[UIImageView alloc] initWithFrame:CGRectMake(mainSize.width / 2 - 211 / 2, 100, 211, 109)];
    imgLogin.image = [UIImage imageNamed:@"owl-login"];
    imgLogin.layer.masksToBounds = YES;
    [self.view addSubview:imgLogin];
    
    imgLeftHand = [[UIImageView alloc] initWithFrame:rectLeftHand];
    imgLeftHand.image = [UIImage imageNamed:@"owl-login-arm-left"];
    [imgLogin addSubview:imgLeftHand];
    
    imgRightHand = [[UIImageView alloc] initWithFrame:rectRightHand];
    imgRightHand.image = [UIImage imageNamed:@"owl-login-arm-right"];
    [imgLogin addSubview:imgRightHand];
    
    UIView *vLogin = [[UIView alloc] initWithFrame:CGRectMake(15, 200, mainSize.width - 30, 160)];
    vLogin.layer.cornerRadius = 10;
    vLogin.layer.borderWidth = 0.5;
    vLogin.layer.borderColor = [[UIColor grayColor] CGColor];
    vLogin.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:vLogin];
    
    imgLeftHandGone = [[UIImageView alloc] initWithFrame:rectLeftHandGone];
    imgLeftHandGone.image = [UIImage imageNamed:@"icon_hand"];
    [self.view addSubview:imgLeftHandGone];
    
    imgRightHandGone = [[UIImageView alloc] initWithFrame:rectRightHandGone];
    imgRightHandGone.image = [UIImage imageNamed:@"icon_hand"];
    [self.view addSubview:imgRightHandGone];
    
    txtUser = [[UITextField alloc] initWithFrame:CGRectMake(30, 30, vLogin.frame.size.width - 60, 44)];
    txtUser.delegate = self;
    txtUser.layer.cornerRadius = 5;
    txtUser.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    txtUser.layer.borderWidth = 0.5;
    txtUser.returnKeyType = UIReturnKeyNext;
    txtUser.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    txtUser.leftViewMode = UITextFieldViewModeAlways;
    UIImageView* imgUser = [[UIImageView alloc] initWithFrame:CGRectMake(11, 11, 22, 22)];
    imgUser.image = [UIImage imageNamed:@"iconfont-user"];
    [txtUser.leftView addSubview:imgUser];
    self.userTF = txtUser;
    [vLogin addSubview:txtUser];
    
    txtPwd = [[UITextField alloc] initWithFrame:CGRectMake(30, 90, vLogin.frame.size.width - 60, 44)];
    txtPwd.delegate = self;
    txtPwd.layer.cornerRadius = 5;
    txtPwd.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    txtPwd.layer.borderWidth = 0.5;
    txtPwd.secureTextEntry = YES;
    txtPwd.returnKeyType = UIReturnKeyDone;
    txtPwd.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    txtPwd.leftViewMode = UITextFieldViewModeAlways;
    UIImageView* imgPwd = [[UIImageView alloc] initWithFrame:CGRectMake(11, 11, 22, 22)];
    imgPwd.image = [UIImage imageNamed:@"iconfont-password"];
    [txtPwd.leftView addSubview:imgPwd];
    self.passwordTF = txtPwd;
    [vLogin addSubview:txtPwd];
    
    CGFloat margin = 20;
    CGFloat buttonY = CGRectGetMaxY(vLogin.frame) + margin;
    CGFloat buttonW = Width * 0.3;
    CGFloat loginX = Width * 0.5 - margin - buttonW;
    CGFloat buttonH = 30;
    UIButton *loginButton = [[UIButton alloc]initWithFrame:CGRectMake(loginX, buttonY, buttonW, buttonH)];
    [loginButton setTitle:@"登陆" forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(userLogin) forControlEvents:UIControlEventTouchUpInside];
    loginButton.layer.cornerRadius = 10;
    loginButton.layer.masksToBounds = YES;
    loginButton.backgroundColor = kThemeColor;
    [self.view addSubview:loginButton];
    
    CGFloat registerX = Width * 0.5 + margin;
    UIButton *registerButton = [[UIButton alloc]initWithFrame:CGRectMake(registerX, buttonY, buttonW, buttonH)];
    [registerButton addTarget:self action:@selector(pushToRegister) forControlEvents:UIControlEventTouchUpInside];
    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
    registerButton.backgroundColor = kThemeColor;
    registerButton.layer.cornerRadius = 10;
    registerButton.layer.masksToBounds = YES;
    [self.view addSubview:registerButton];
    
}

- (void) registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}

- (void) keyboardWasShown:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    NSLog(@"keyBoard:%f", keyboardSize.height);
    CGFloat viewHeight = CGRectGetMaxY(self.currentTF.frame) + 200 + 10;
    NSLog(@"%f", Height - keyboardSize.height - 64);
    if (viewHeight > Height - keyboardSize.height) {
        CGFloat change = keyboardSize.height - (Height - viewHeight);
        NSLog(@"%f", change);
        self.view.center = CGPointMake(self.view.center.x, Height * 0.5 - change);
    }
    
}
- (void) keyboardWasHidden:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    NSLog(@"keyboardWasHidden keyBoard:%f", keyboardSize.height);
    // keyboardWasShown = NO;
    self.view.center = CGPointMake(Width * 0.5, Height * 0.5);
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField isEqual:txtUser]) {
        [self.passwordTF becomeFirstResponder];
    }
    else if ([textField isEqual:txtPwd])
    {
        [self hiddenKeyboard];
    }
    return YES;
}

- (void)hiddenKeyboard
{
    [self.view endEditing:YES];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.currentTF = textField;

    if ([textField isEqual:txtUser]) {
        if (showType != JxbLoginShowType_PASS)
        {
            showType = JxbLoginShowType_USER;
            return;
        }
        showType = JxbLoginShowType_USER;
        [UIView animateWithDuration:0.5 animations:^{
            imgLeftHand.frame = CGRectMake(imgLeftHand.frame.origin.x - offsetLeftHand, imgLeftHand.frame.origin.y + 30, imgLeftHand.frame.size.width, imgLeftHand.frame.size.height);
            
            imgRightHand.frame = CGRectMake(imgRightHand.frame.origin.x + 48, imgRightHand.frame.origin.y + 30, imgRightHand.frame.size.width, imgRightHand.frame.size.height);
            
            
            imgLeftHandGone.frame = CGRectMake(imgLeftHandGone.frame.origin.x - 70, imgLeftHandGone.frame.origin.y, 40, 40);
            
            imgRightHandGone.frame = CGRectMake(imgRightHandGone.frame.origin.x + 30, imgRightHandGone.frame.origin.y, 40, 40);
            
            
        } completion:^(BOOL b) {
        }];
        
    }
    else if ([textField isEqual:txtPwd]) {
        if (showType == JxbLoginShowType_PASS)
        {
            showType = JxbLoginShowType_PASS;
            return;
        }
        showType = JxbLoginShowType_PASS;
        [UIView animateWithDuration:0.5 animations:^{
            imgLeftHand.frame = CGRectMake(imgLeftHand.frame.origin.x + offsetLeftHand, imgLeftHand.frame.origin.y - 30, imgLeftHand.frame.size.width, imgLeftHand.frame.size.height);
            imgRightHand.frame = CGRectMake(imgRightHand.frame.origin.x - 48, imgRightHand.frame.origin.y - 30, imgRightHand.frame.size.width, imgRightHand.frame.size.height);
            
            
            imgLeftHandGone.frame = CGRectMake(imgLeftHandGone.frame.origin.x + 70, imgLeftHandGone.frame.origin.y, 0, 0);
            
            imgRightHandGone.frame = CGRectMake(imgRightHandGone.frame.origin.x - 30, imgRightHandGone.frame.origin.y, 0, 0);
            
        } completion:^(BOOL b) {
        }];
    }
}

- (void)dismissLoginVC
{
    [self hiddenKeyboard];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)pushToRegister
{
    [self hiddenKeyboard];
    MHRegistViewController *registerVC = [[MHRegistViewController alloc]init];
    __weak MHLoginViewController *test = self;
    registerVC.autoLoginBlock = ^(NSString *email, NSString *password)
    {
        [test requestDataWithUser:email password:password];
    };
    [self.navigationController pushViewController:registerVC animated:YES];
}

- (void)userLogin
{
    [self hiddenKeyboard];
    if (_userTF.text.length != 0 && _passwordTF.text.length != 0) {
        if ([self isValidateEmail:_userTF.text])
        {
            [self requestDataWithUser:_userTF.text password:_passwordTF.text];
        }
        else
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请正确输入邮箱" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
    else
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"邮箱或密码不能为空" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)requestDataWithUser:(NSString *)email password:(NSString *)password
{
    //    http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx?email=jza1314520@qq.com&method=login&pwd=19920419
    NSDictionary *dict = [ NSDictionary dictionaryWithObjects:@[email,@"login",password] forKeys:@[@"email",@"method",@"pwd"]];
    [[AFHTTPRequestOperationManager manager] GET:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx" parameters:dict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"%@",responseObject);
        
        // 判定返回的结果。
        _result =  [responseObject[@"UserResult"] integerValue];
        if (_result == 1) {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setBool:YES forKey:@"isLogin"];
            [defaults synchronize];
            NSDictionary *infoDict = responseObject[@"UserModel"];
            [self.userInfo setValuesForKeysWithDictionary:infoDict];
            [[MHDataManager shareManager] deleteUserInfo];
            [[MHDataManager shareManager] insertUserInfo:self.userInfo];
            [MHUserInfoSington sharedInstance].userInfo = self.userInfo;
            [[[SDWebImageManager alloc]init] downloadImageWithURL:[NSURL URLWithString:self.userInfo.UserPhotoURL] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                self.userInfo.icon = image;
                [[MHDataManager shareManager]insertUserIcon:image UserInfo:self.userInfo];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"login" object:nil userInfo:[NSDictionary dictionaryWithObject:image forKey:@"image"]];

            }];
            if (self.passUserInfoBlock != nil) {
                self.passUserInfoBlock(_userInfo);
            }
            if (self.successLoginBlock!=nil) {
                self.successLoginBlock();
            }
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }else
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"邮箱或密码错误" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

-(BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
@end
